<%@page import="com.buss.product.utils.ProductStaticParam"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="../includes/tag.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Wcms内容管理系统</title>
    <script type="text/javascript" src="<%=basePath%>resources/lib/jquery/jquery.js"></script>
    <script type="text/javascript" src="<%=basePath%>resources/lib/webui/buss.ui.core.js"></script>
    <script type="text/javascript" src="<%=basePath%>resources/lib/webui/buss.ui.js"></script>
	<script type="text/javascript" src="<%=basePath%>resources/lib/jqgrid/js/i18n/grid.locale-cn.js"></script>
	<script type="text/javascript" src="<%=basePath%>resources/lib/jqgrid/js/jquery.jqGrid.min.js"></script>
	<script type="text/javascript" src="<%=basePath%>resources/lib/public.js"></script>
	
	<link rel="stylesheet" type="text/css" href="<%=basePath%>resources/lib/styles/themes/buss-ui.css">
	<link rel="stylesheet" type="text/css" href="<%=basePath%>resources/lib/jqgrid/css/jquery-ui.css">
	<link rel="stylesheet" type="text/css" href="<%=basePath%>resources/lib/jqgrid/css/ui.jqgrid.css">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>resources/styles/public.css">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>resources/styles/icon.css">

	<script type="text/javascript">
		$(document).ready(function(){						
			setGridData();
			loadTree();
			getBrand("0");
			resize();
			$(window).resize(resize);
			$("#search-btn").button({iconCls:'icon-search',handler:function(){
    			var jsonParam = syscore.formToJson($("#_searchForm"));
				$("#tabledata").jqGrid("setGridParam",{page:1,postData:jsonParam}).trigger("reloadGrid");
			}});
			$("#search-clear").button({iconCls:'icon-cancel',handler:function(){
				$("#_searchForm").resetForm();
    			$("#search-btn").trigger("click");
			}});
			$("#add-btn").button({iconCls:'icon-add',handler:function(){
				var node = $("#catagoryTree").treeview("getSelectedNode");
				if(!node || node.id == '0'){
					$.alert('提示','请选择要增加商品的的分类!',300,140,'info');
					return;
				}
				editPage("addpage",node.id);				
			}});		
			$("#edit-btn").button({iconCls:'icon-edit',handler:function(){
				var selRows = $("#tabledata").jqGrid('getGridParam',"selarrrow");
				if(selRows == 0){
					$.alert('提示','你没有选择要修改的数据!',300,140,'info');
					return;
				}
				if(selRows.length > 1){
					$.alert('提示','只能选择一条数据，请重新选择!',300,140,'info');
					return;
				}
				editPage("editpage",selRows[0]);				
			}});
			$("#del-btn").button({iconCls:'icon-remove',handler:function(){
				var selRows = $("#tabledata").jqGrid('getGridParam',"selarrrow");
				if(selRows == 0){
					$.alert('提示','你没有选择要删除的数据!',300,140,'info');
					return;
				}
				$.confirm('提示','确认要删除选中数据吗?',300,140,function(){
					var str = "";
					for(var i = 0;i < selRows.length;i++){
						if(i < selRows.length - 1){
							str += "ids=" + selRows[i] + "&";
						}else{
							str += "ids=" + selRows[i];
						}
					}
					$.post("<%=basePath%>admin/goods/delete.do",str,function(rsData){
						if(rsData.message.code != '0'){
							$.alert('错误','删除商品信息失败!原因:' + rsData.message.mess,300,140,'error');
							return;
						}
						$("#tabledata").jqGrid({page:1}).trigger('reloadGrid');
					},"json");
				});				
			}});
			
			$("select[name='brandId']").combo({
				filter:true
			});
		});
		
		/**编辑属性页面*/
    	function editPage(type,id){    		
    		var url = "<%=basePath%>admin/goods/";
    		var pageUrl = "";
    		var saveUrl = "";
    		var title = "新增商品信息";
    		if(type == "editpage"){
    			title = "修改商品信息";
    			saveUrl = url + "edit.do";
    			pageUrl = url + "editpage.do?id=" + id;
    		}else{
    			saveUrl = url + "add.do";
    			pageUrl = url + "addpage.do?id=" + id;
    		}
    		var editDlg = $("<div/>").dialog({
    			modal:true,
    			header:true,
    			height:500,
    			width:700,
    			title:title,
    			closable:true,
    			minimizable:false,
    			collapsible:false,
    			iconCls:'icon',
    			loadUrl:pageUrl,
    			buttons:[
    			    {text:'保  存',type:'button',iconCls:'icon-save',handler:function(){
    			    	var returnFlag = false;
    			    	var selObjs = editDlg.find(".hiden_singleSel[entryway='list']");
    			    	for(var i = 0;i < selObjs.length;i++){
    			    		var obj = selObjs[i];
    			    		var name = $(obj).attr("data");
    			    		var title = $(obj).attr("title");
    			    		/*var length = editDlg.find("input[name='"+name+"']:checked").length;
    			    		if(length == 0){
    			    			$.alert("提示",title + "必须至少选择一项!",300,140,"info");
    			    			return;
    			    		}*/
    			    	}
    			    	selObjs = editDlg.find(".hiden_singleSel[entryway='manual']");
    			    	for(var i = 0;i < selObjs.length;i++){
    			    		var obj = selObjs[i];
    			    		var name = $(obj).attr("data");
    			    		var title = $(obj).attr("title");
    			    		var length = editDlg.find("input[name='"+name+"'][type='text']").length;
    			    		/*if(length == 0){
    			    			$.alert("提示",title + "必须至少选择一项!",300,140,"info");
    			    			return;
    			    		}*/
    			    		var textObjs = editDlg.find("input[name='"+name+"'][type='text']");
    			    		for(var j = 0;j < textObjs.length;j++){
    			    			var tObj = textObjs[j];    			    			
    			    			/*if($(tObj).val().trim() == ""){
    			    				$.alert("提示",title + "不能为空!",300,140,"info");
    			    				return;
    			    			}*/
    			    		}
    			    	}

    			    	editDlg.find("form").attr("action",saveUrl);
    			    	syscore.ajaxSubmit(editDlg.find("form"),function(rsData){
    			    		if(rsData.message.code != "0"){
    			    			$.alert('提示','保存数据失败!原因:' + rsData.message.mess,300,140,'error');
    							return false;
    			    		}else{
    			    			$("#tabledata").jqGrid().trigger('reloadGrid');				        			 	
    			    			editDlg.dialog("destroy");
    			    		}
    			    	});
    			    }},
    			    {text:'关  闭',type:'button',iconCls:'icon-cancel',handler:function(){
    			    	editDlg.dialog("destroy");
    			    }}
    			],
    			onLoad:function(){
    				editDlg.find("#goods_edit ul").idTabs("goods_base");
        			editDlg.find("#goods_edit select[name='brand.id']").combo({
        				filter:true,
        				onChange:function(newValue,oldValue){
        					//alert(newValue);
        				}
        			});
        			var skuSelect = editDlg.find("#goods_edit select[name='sku']").combo({
        				filter:true,
        				bottomTools:[
        				             {iconCls:'icon-add',text:'新增',handler:function(){
        				            	 dicDataEdit("<%=ProductStaticParam.PRODUCT_UNIT_CODE%>",editDlg,skuSelect);
        				             }}
        				             ]
        			});
        			var entryUnitSelect = editDlg.find("#goods_edit select[name='entryUnit']").combo({
        				filter:true,
        				bottomTools:[
        				             {iconCls:'icon-add',text:'新增',handler:function(){
        				            	 dicDataEdit("<%=ProductStaticParam.PRODUCT_UNIT_CODE%>",editDlg,entryUnitSelect);
        				             }}
        				             ]
        			});
        			var exUnitSelect = editDlg.find("#goods_edit select[name='exUnit']").combo({
        				filter:true,
        				bottomTools:[
        				             {iconCls:'icon-add',text:'新增',handler:function(){
        				            	 dicDataEdit("<%=ProductStaticParam.PRODUCT_UNIT_CODE%>",editDlg,exUnitSelect);
        				             }}
        				             ]
        			});
        			
        			$(".single_input[type='text']").focusout(function(){
        				changeProductDetail(editDlg,false);
        			});
        			
        			$('.addSpan').die().live('click',function(){
        				var name = $(this).parent().find("input[type='text']").attr("name");
        				var span = $("<span style='display:block;margin-bottom:2px;'>"+
        						"<input type='text' name='"+name+"' size='30' class='text' value=''/>" +
        						"<a href='javascript:void(0);' class='addSpan' style='margin-left:5px;'><span class='bs-button-text icon-add' style='width:18px;'>&nbsp;</span></a>" +
        						"<a href='javascript:void(0);' class='removeSpan' style='margin-left:5px;'><span class='bs-button-text icon-remove' style='width:18px;'>&nbsp;</span></a>" +
        						"</span>");        	
        				span.find("input[type='text']").focusout(function(){
        					changeProductDetail(editDlg,false);
        				});
        				$(this).parent().after(span);
        				$(this).hide();
        				$(this).next().show();
        			});
        			$(".removeSpan").die().live('click',function(){
        				var obj = $(this).parent().parent();
        				var cnt = $(this).parent().parent().children().length;
        				
        				if($(this).parent().next().length == 0){
        					$(this).parent().prev().find(".addSpan").show();
        				}
        				$(this).parent().remove();
        				if(cnt == 3){
        					obj.find(".removeSpan").hide();
        				}
        				changeProductDetail(editDlg,false);
        			});
        			editDlg.find("input[name='name']").focusout(function(){
    					var hanzi = $(this).val();
    					$.post("<%=basePath%>core/hanzitopinyin.do",{hanzi:hanzi},function(rsData){
    						if(rsData.message.code != 0){
    							editDlg.find("input[name='pinyin']").val("");
    							editDlg.find("input[name='pinyinHead']").val("");
    						}else{
    							editDlg.find("input[name='pinyin']").val(rsData.pinyinfull);   
    							editDlg.find("input[name='pinyinHead']").val(rsData.pinyin);
    						}
    					},"json");
    				});
        			changeProductDetail(editDlg,true);
        			editDlg.find(".single_checkbox").change(function(){
        				changeProductDetail(editDlg,false);
        			});
    			}
    		});
    		editDlg.dialog("loadPage");
    	}
		
		/**动态显示隐藏商品属性明细信息列表*/
		function changeProductDetail(editDlg,isLoad){
			var singleParams = new Array();
			var names = new Array();
			var titles = new Array();
			var index = 0;
			editDlg.find(".hiden_singleSel").each(function(i){
				var name = $(this).attr("data");
				var tmpArr = new Array();
				names[i] = name;
				if(editDlg.find("input[name='"+name+"'][type='checkbox']:checked").length > 0){
					editDlg.find("input[name='"+name+"'][type='checkbox']:checked").each(function(j){        						
						tmpArr[j] = $(this).val();
					});
				}
				editDlg.find("input[name='"+name+"'][type='text']").each(function(j){
					if($(this).val().trim() != ""){
						tmpArr[j] = $(this).val();
					}
				});
			/*	else{
					editDlg.find("input[name='"+name+"'][type='text']").each(function(j){
						tmpArr[j] = $(this).val();
					});
				}*/
				
				if(tmpArr.length > 0){
					singleParams[index] = tmpArr;
					titles[index] = $(this).attr("title");
					index++;
				}
			});
			
			var b = new Array();
			for(var i = 0;i < singleParams.length;i++){
				b[i] = 0;
			}
			var length = singleParams.length;
			if(!isLoad){
				editDlg.find("#old_details").children().remove();
				editDlg.find("#product_details tbody tr").each(function(){
					var tmpPid = $(this).find("input[name='product_pIds']").val();
					var tmpBarCode = $(this).find("input[name='barCode']").val();
					var tmpPrice = $(this).find("input[name='product_price']").val();
					var tmpDetails = $(this).find("input[name='product_details']").val();
					var input = $("<input type='hidden' data='' pId='"+tmpPid+"' barcode='"+tmpBarCode+"' price='"+tmpPrice+"'/>");
					input.attr("data",tmpDetails);
					editDlg.find("#old_details").append(input);
				});
			}
			editDlg.find("#product_details").children().remove();
			if(titles.length > 0){
				var th = "<thead><tr>";         				
				for(var i = 0;i < titles.length;i++){
					th += "<th height='30'>"+titles[i]+"</th>";
				}
				th += "<th width='150'>商品条码</th>";
				th += "<th width='100'>销售单价</th>"
				th += "</tr></thead>"
				editDlg.find("#product_details").append(th);
				editDlg.find("#product_details thead tr th").addClass("table_title");
				editDlg.find("#product_details thead tr th").css("border","1px solid #A6C9E2");
				editDlg.find("#product_details thead tr th").css("border-left","none");
				editDlg.find("#product_details").append("<tbody/>");
				do{		
					var singleStr = "";
					var titleStr = "";
					var tr = "<tr>";
					var barCode = "";
					var pId = "";
					var price = "0";
					for(var i = 0;i < length;i++){
						tr += "<td>"+singleParams[i][b[i]]+"</td>";
						if(i < length - 1){
							singleStr += "'" + names[i] + "':'" + singleParams[i][b[i]] + "',"; 
							titleStr += "'" + titles[i] + "':'" + singleParams[i][b[i]] + "',";
						}else{
							singleStr += "'" + names[i] + "':'" + singleParams[i][b[i]] + "'";
							titleStr += "'" + titles[i] + "':'" + singleParams[i][b[i]] + "'";
						}
					}
					var tStr = singleStr.split(",");
					trStr = tStr.sort();
					editDlg.find("#old_details input").each(function(){
						var tmpStr = $(this).attr("data");						
						tmpStr = tmpStr.split(",").sort();
						if(trStr.toString() == tmpStr.toString()){
							barCode = $(this).attr("barCode");
							pId = $(this).attr("pId");
							price = $(this).attr("price");
							return;
						}
					});
					
					if (singleStr != ""){
						tr += "<td><input type='text' style='width:100%;' name='barCode' value='"+barCode+"' class='text'><input type='hidden' name='product_pIds' value='"+pId+"'/></td>";
						tr += "<td><input type='text' style='width:100%;' name='product_price' value='"+price+"' class='text'><input type='hidden' name='product_details' value=''/><input type='hidden' name='product_details_title' value=''/></td>";						
						tr += "</tr>";
						tr = $(tr);
						tr.find("input[name='product_details']").val(singleStr);
						tr.find("input[name='product_details_title']").val(titleStr);
						editDlg.find("#product_details tbody").append(tr);
						editDlg.find("#product_details tbody tr td").css("border","1px solid #A6C9E2");
						editDlg.find("#product_details tbody tr td").css("border-top","none");
						editDlg.find("#product_details tbody tr td").css("border-left","none");
						editDlg.find("#product_details").css("border-left","1px solid #A6C9E2");
					}
				}while(register(singleParams,b));        				
			}else{

				barCode = editDlg.find("#old_details input").attr("barCode");
				pId = editDlg.find("#old_details input").attr("pId");
				price = editDlg.find("#old_details input").attr("price");
				
				var tr = "<tr>";
				tr += "<td width='80' align='right' valign='top'>商品条码：</td>";
				tr += "<td><input type='hidden' name='product_pIds' value='"+pId+"'/><input type='text' size='30' name='barCode' class='text' value='"+barCode+"'/></td>";
				tr += "</tr>";
				tr +="<tr>";
				tr += "<td width='80' align='right' valign='top'>销售单价：</td>";
				tr += "<td><input type='text' size='30' name='product_price' class='text' value='"+price+"'/></td>";
				tr += "</tr";
				editDlg.find("#product_details").append(tr);
			}
		}
		/**计算数组交集*/
		function register(a,b){
			var s = b.length;
			for(var i = s - 1;i >= 0 ;--i){
				if(b[i] + 1 < a[i].length){
					b[i] = b[i] + 1;
					return true;
				}else if(i - 1 >= 0){
					b[i] = 0;
				}else
					return false;
			}
			return false;
		}
		
    	function dicDataEdit(code,dlgParam,selectObj){
			var pageUrl = "<%=basePath%>admin/dicdata/";
			var saveUrl = "<%=basePath%>admin/dicdata/";
			var title = "新增商品单位信息";
			pageUrl += "extaddpage.do";
			saveUrl += "add.do";
			var dlg = syscore.editDialog(title,pageUrl,'code=' + code,450,250,saveUrl,function(rsData){
				if(rsData.message.code != '0'){
					 $.alert('提示','保存数据失败!原因:' + rsData.message.mess,300,140,'error');
					 return false;
				 }else{
					 var name = dlg.find("input[name='name']").val();
					 dlgParam.find("#goods_edit select[name='sku']").combo("addItem",name,name);
					 dlgParam.find("#goods_edit select[name='sku']").combo("refresh");
					 dlgParam.find("#goods_edit select[name='entryUnit']").combo("addItem",name,name);
					 dlgParam.find("#goods_edit select[name='entryUnit']").combo("refresh");
					 dlgParam.find("#goods_edit select[name='exUnit']").combo("addItem",name,name);
					 dlgParam.find("#goods_edit select[name='exUnit']").combo("refresh");					 
					 selectObj.combo("changeValue",name);
      			 	 dlg.dialog("destroy");
				 }
			},function(){
				
			});
		}
		
		
		function setGridData(){
			var url = "<%=basePath%>admin/goods/list.do?categoryIds=0";
			var colNames = ['编码','商品名称', '商品货号','所属分类','品牌','固定价格','当前状态'];
			var colModel = [
			                {name:'code',index:'code', width:80,align:'left'},
						    {name:'name',index:'name', width:150,align:'left'},							 
							{name:'styleNo',index:'styleNo', width:80,align:'center'}, 
							{name:'category.name',index:'categoryName',width:100,align:'left',sortable:true},
							{name:'brand.name',index:'brandName',width:100,align:'left'},
							{name:'isFixed',index:'isFixed',width:80,align:'center',formatter:function(cellVal){
								if(cellVal){
									return "是";
								}else{
									return "否";
								}
							}},
							{name:'status',index:'status',width:80,align:'center',formatter:syscore.formaterStatus}
						];
			syscore.setGridData("#tabledata","tablepage",url,colNames,colModel,true);
		}	
		
		function loadTree(){
			var root = [{
				id:"0",
				code:'catetory_root',
				name:'商品分类信息',			
				isParent:true,
				subCategories:true,
				open:true
			}];
			$("#catagoryTree").treeview({
				treeNodeKey:'id',
				treeNodeParentKey:'parentId',
				hasChildKey:'subCategories',
				nameCol:'name',
				expandSpeed:"",
				asyncParamOther:["isPage",false],
				async:true,
				asyncUrl:function(treeNode){
					return "<%=basePath%>admin/goodscategory/list.do?parentId=" + treeNode.id;	
				},
				root:{isRoot:true,nodes:root},
				callback:{
					beforeAsyncSuccess:function(msg){
						if(msg.message.code == '-2'){
							$.alert('提示','你还没有登录或Session已经过期，请重新登录系统!',300,170,'info');
							return false;
						}
						if(msg.message.code == "-1"){
							$.alert("提示","获取信息失败，原因：" + msg.message.mess,300,170,'error');
							return false;
						}
						return true;
					},
					click:function(event,treeId,treeNode){
						var url = $("#tabledata").jqGrid("getGridParam","url");
						getBrand(treeNode.id);
						$("#tabledata").jqGrid("setGridParam",{"url":"<%=basePath%>admin/goods/list.do?categoryIds="+treeNode.id}).trigger('reloadGrid');
					}
				}
			});
		}

		function getBrand(categoryId){
			$.post("<%=basePath%>admin/brand/list.do?categoryId=" + categoryId,"",function(rsData){
				if(rsData.message.code != '0'){
					$.alert("提示","获取品牌信息失败，原因：" + rsData.message.mess,300,170,'error');
					return;
				}
				$("select[name='brandId']").html("");
				var opt = "<option value=''>--选择品牌--</option>";
				$("select[name='brandId']").append(opt);
				for(var i = 0;i < rsData.result.data.length;i++){
					opt = "<option value='"+rsData.result.data[i].id+"'>"+rsData.result.data[i].name+"</option>";
					$("select[name='brandId']").append(opt);
				}
				$("select[name='brandId']").combo("refresh");
			},"json");			
		}
		function resize(){
			var h = $(window).height() - $(".nav_curloc").outerHeight() - $(".nav_search").outerHeight() - $(".nav_btn_bar").outerHeight() - 10;
			$(".context").height(h);
			$("#tabledata").jqGrid("setGridHeight",h - 50);
			$("#tabledata").jqGrid("setGridWidth",$(window).width() - $("#catagoryTree").parent().width() - 12);
		}
		
	</script>
  </head>
  
  <body>
  	<div style="border-right:1px solid #68C4E9;position:absolute;width:180px;height:100%;left:0;overflow:auto;">
  		<ul id="catagoryTree" class="tree"></ul>
  	</div>
  	<div style="height:100%;margin:0 0 0 181px;position:relative;">
  		<div class="nav_curloc">
	    	<label>您的当前位置：<bstag:navbar menuId="${menuid}"/></label>
	    </div>
	     <div class="nav_search" style="height:56px;">
	     	<form id='_searchForm' action="" name="_searchForm">
		    	<table height="100%" cellpadding="0" cellspacing="0">
		    		<tr>
		    			<td valign="middle" align="right">商品名称：</td>
		    			<td valign="middle" align="left">
		    				<input type="text" size="20" maxlength="100" class="text" name="name"/>
		    			</td>
		    			<td valign="middle" style="padding-left:5px;" align="right">拼音码：</td>
		    			<td valign="middle" align="left">
		    				<input type="text" size="20" maxlength="100" class="text" name="pinyin"/>
		    			</td>
		    		</tr>
		    		<tr>
		    			<td valign="middle" align="right">商品货号：</td>
		    			<td valign="middle" align="left">
		    				<input type="text" size="20" maxlength="20" class="text" name="styleNo"/>
		    			</td>
		    			<td valign="middle" align="right">商品品牌：</td>
		    			<td valign="middle"  align="left" style="padding-left:2px;">
		    				<select name="brandId" style="width:128px;">
		    				</select>
		    			</td>
		    			
		    			<td style="padding-left:5px;">
		    				<a id="search-btn" href="javascript:void(0);">查 询</a>
		    			</td>
		    			<td style="padding-left:5px;">
			    			<a id="search-clear" href="javascript:void(0);">清 空</a>
			    		</td>
		    		</tr>
		    	</table>
	    	</form>
	    </div>
	    <div class="nav_btn_bar">
	    	<table height="100%" cellpadding="0" cellspacing="0">
	    		<tr>
	    			<td valign="middle">
	    				<a id="add-btn" href="javascript:void(0);">新 增</a>
	    			</td>
	    			<td valign="middle"" style="padding-left:5px;">
	    				<a id="edit-btn" href="javascript:void(0);">修 改</a>
	    			</td>
	    			<td valign="middle" style="padding-left:5px;">
	    				<a id="del-btn" href="javascript:void(0);">删 除</a>
	    			</td>
	    		</tr>
	    	</table>
	    </div>
	    <div class="context">
	    	<table id="tabledata"></table>
	    	<div id="tablepage"></div>
	    </div>
  	</div>     
  </body>
</html>
